package com.heatup.apt.management.service.custom.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.user.UserAccountConsumeMapper;
import com.heatup.apt.common.dao.user.UserAccountRechargeMapper;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.management.pay.RefundUtil;
import com.heatup.apt.management.service.custom.UserAccountConsumeService;
import com.heatup.apt.management.service.custom.UserAccountRechargeService;
import com.heatup.apt.model.management.SysUser;
import com.heatup.apt.model.order.OrderInfo;
import com.heatup.apt.model.order.OrderRefund;
import com.heatup.apt.model.user.UserAccountConsume;
import com.heatup.apt.model.user.UserAccountRecharge;
import com.heatup.apt.model.user.UserInfo;

/**
 * C端用户消费记录服务实现类
 * @author jixiangyun
 * 2016年12月17日 上午9:56:28
 */
@Service
public class UserAccountConsumeServiceImpl extends  SuperServiceImpl<UserAccountConsumeMapper,UserAccountConsume> implements UserAccountConsumeService{
	
	private static final Logger logger = LoggerFactory.getLogger(UserAccountConsumeServiceImpl.class);
	@Autowired
	private UserAccountConsumeMapper userAccountConsumeMapper;
	
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	@Autowired
	private UserAccountRechargeMapper userAccountRechargeMapper;
	
	@Autowired
	private UserAccountRechargeService userAccountRechargeService;
	
	/**
	 * 分页查询
	 */
	@Override
	public Map queryUserAccountConsumePage(Map<String, Object> paramsMap) {
		Map<String,Object> responseMap = new HashMap<String, Object>();
		Integer pageNo = (Integer) paramsMap.get("pageNo");
		Integer pageSize = (Integer) paramsMap.get("pageSize");
		Integer userId= (Integer) paramsMap.get("userId");
		Integer orderType= (Integer) paramsMap.get("orderType");
		Integer orderId = (Integer) paramsMap.get("orderId");
		String createTime = (String) paramsMap.get("createTime");
		Page<UserAccountConsume> userAccountConsumePage = new Page<>(pageNo,pageSize);
		List<UserAccountConsume> list = userAccountConsumeMapper.queryUserAccountConsumegPage(userAccountConsumePage, paramsMap);
		userAccountConsumePage.setRecords(list);
		BigDecimal consumeAmt = userAccountConsumeMapper.getAmountByUserIdAddOrderType(userId,orderType,orderId,createTime);
		/*responseMap.put("list",list);
		responseMap.put("pageNo",pageNo);
		responseMap.put("pageSize", pageSize);
		responseMap.put("orderType",paramsMap.get("orderType"));*/
		paramsMap.put("list", list);
		paramsMap.put("pageCount",userAccountConsumePage.getTotal());
		paramsMap.put("accountConsum", consumeAmt);
		if(orderId == 0){
			paramsMap.put("orderId", null);
		}
		return paramsMap;
	}
	
	/**
	 * 用户退款
	 */
	@Override
	public Map refundToUserAccountConsumeByOrderNumber(Map<String, Object> paramsMap) {
		logger.info("=================refundToUserAccountConsumeByOrderNumber start =======================================");
		String order_number = (String) paramsMap.get("order_number");
		String amt = (String) paramsMap.get("amt");
		Integer consume_id = (Integer) paramsMap.get("consume_id");
		BigDecimal refun_amt = new BigDecimal(amt);
		String remark = (String) paramsMap.get("remark");
		OrderInfo orderInfo = orderInfoMapper.queryOrderInfoByNumber(order_number);
		int count = orderInfoMapper.queryOrderRefundByOrderId(orderInfo.getId());
		// 查询用户的充值记录
		UserAccountRecharge userAccountRecharge = new UserAccountRecharge();
		userAccountRecharge.setChangeCode(order_number);
		userAccountRecharge.setId(consume_id);
		userAccountRecharge = userAccountRechargeMapper.selectById(consume_id);
		
		Map<String, Object> refundMap = new HashMap<String,Object>();
		paramsMap.put("bool", true);
		// 这里是防止多笔退款
		if(count > 0){
			paramsMap.put("bool", true);
			logger.info("=================refundToUserAccountConsumeByOrderNumber:已经退过款了直接返回 =======================================");
			
		}else{
			if(orderInfo != null && (OrderContants.PayStatus.PAEING.equals(orderInfo.getPayStatus()) || OrderContants.PayStatus.PAID.equals(orderInfo.getPayStatus()))){
				// 在这里要做一个可退金额的判断
				// 
				UserInfo userInfo  = userInfoMapper.selectById(orderInfo.getUserId());
				SysUser sysUser = (SysUser)paramsMap.get("sys_user");
				paramsMap.put("userInfo", userInfo);
				Map<String,Object> maps = userAccountRechargeService.calculationRdfundAmt(paramsMap);
				BigDecimal refundAmt = (BigDecimal) maps.get("refunAmt");
				int num = (int) maps.get("num");
				if(refundAmt.compareTo(BigDecimal.ZERO) != 0){
					refundMap = RefundUtil.wechatRefund1(orderInfo.getOrderNumber(), orderInfo.getAmount(), refun_amt);
					
					if("FAIL".equals(refundMap.get("result_code"))){
						logger.info("=================refundToUserAccountConsumeByOrderNumber error:退款失败 =======================================");
						paramsMap.put("bool", false);
						paramsMap.put("msg","退款失败");
						if("NOTENOUGH".equals(refundMap.get("err_code"))){
							paramsMap.put("bool", false);
							paramsMap.put("msg","我们公司账户余额不足以退款");
							logger.info("=================refundToUserAccountConsumeByOrderNumber error:公司账户余额不足 =======================================");
						}
						return paramsMap;
					}else if("SUCCESS".equals(refundMap.get("result_code"))){
						logger.info("=================refundToUserAccountConsumeByOrderNumber :退款成功开始插入退款表中 =======================================");
						List<OrderRefund> listR = new ArrayList<>();
						// 插入退款记录 微信退款
						OrderRefund orderR = new OrderRefund();
						orderR.setOrderId(orderInfo.getId());
						orderR.setRefundType(orderInfo.getPayType());
						orderR.setRefundNo((String)refundMap.get("refund_id"));
						orderR.setRefundFee(refun_amt.doubleValue());
						orderR.setTotalFee(userAccountRecharge.getActualAmt().doubleValue());
						orderR.setRefundStatus("nprocessing");//这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
						orderR.setUserId(orderInfo.getUserId());
						orderR.setRefundChanne("original");
						orderR.setRefundFashion("1");
						orderR.setCreatedTime(new Date());
						orderR.setCreatedBy(String.valueOf(sysUser.getId()));
						orderR.setRemark("个人储值卡退款,微信退款,原因："+remark);
						// 插入退款记录 个人储值卡退款
						OrderRefund orderU = new OrderRefund();
						orderU.setOrderId(orderInfo.getId());
						orderU.setRefundType(orderInfo.getPayType());
						orderU.setRefundNo((String)refundMap.get("refund_id"));
						orderU.setRefundFee(userAccountRecharge.getActualAmt().subtract(userAccountRecharge.getFaceAmt()).doubleValue());
						orderU.setTotalFee(userAccountRecharge.getActualAmt().doubleValue());
						orderU.setRefundStatus("nprocessing");//这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
						orderU.setUserId(orderInfo.getUserId());
						orderU.setRefundChanne("original");
						orderU.setRefundFashion("1");
						orderU.setCreatedTime(new Date());
						orderU.setCreatedBy(String.valueOf(sysUser.getId()));
						orderU.setRemark("个人储值卡退款,赠送金额退款,原因："+remark);
						listR.add(orderR);
						listR.add(orderU);
						int zhunatai1 = orderInfoMapper.createdRefundOrderList(listR);
						logger.info("=================refundToUserAccountConsumeByOrderNumber :退款成功开始插入退款表中 zhunatai1:"+zhunatai1+"=======================================");
						// 修改订单
						orderInfo.setPayStatus(OrderContants.PayStatus.REFOUND);
						int boolO = orderInfoMapper.updateSelectiveById(orderInfo);
						logger.info("=================refundToUserAccountConsumeByOrderNumber :修改订单表的支付状态 boolO:"+boolO+"=======================================");
						
						BigDecimal u_refund_amt = userAccountRecharge.getActualAmt().subtract(userAccountRecharge.getFaceAmt());
						// 判断当前账户余额是否大于 退款金额+赠送金额
						if(userInfo.getAccountAmt().compareTo(u_refund_amt.add(refun_amt)) < 0){
							paramsMap.put("bool", false);
							paramsMap.put("msg","个人账户余额不足以退款");
						}else{
							userInfo.setAccountAmt(userInfo.getAccountAmt().subtract(u_refund_amt.add(refun_amt)));
							userInfo.setUpdatedTime(new Date());
							userInfo.setUpdatedBy(sysUser.getId());
							int boolU = userInfoMapper.updateSelectiveById(userInfo);
							logger.info("=================refundToUserAccountConsumeByOrderNumber :修改用户的账户余额 boolU:"+boolU+"=======================================");
						}
					}
				}else{
					paramsMap.put("bool", true);
					OrderRefund orderU = new OrderRefund();
					orderU.setOrderId(orderInfo.getId());
					orderU.setRefundType(orderInfo.getPayType());
					orderU.setRefundNo((String)refundMap.get("refund_id"));
					orderU.setRefundFee(userInfo.getAccountAmt().doubleValue());
					orderU.setTotalFee(orderInfo.getAmount().doubleValue());
					orderU.setRefundStatus("nprocessing");//这里统一给退款中,然后在每天跑定时任务的时候在更新状态值
					orderU.setUserId(orderInfo.getUserId());
					orderU.setRefundChanne("original");
					orderU.setRefundFashion("1");
					orderU.setCreatedTime(new Date());
					orderU.setCreatedBy(String.valueOf(sysUser.getId()));
					orderU.setRemark("个人储值卡退款,将用户最后的赠送金额的余额清掉,退款金额为："+userInfo.getAccountAmt());
					int zhunatai = orderInfoMapper.createdRefundOrder(orderU);
					userInfo.setAccountAmt(BigDecimal.valueOf(0));
					userInfo.setUpdatedTime(new Date());
					userInfo.setUpdatedBy(sysUser.getId());
					int boolU = userInfoMapper.updateSelectiveById(userInfo);
					logger.info("=================refundToUserAccountConsumeByOrderNumber :修改用户的账户余额 boolU2:"+boolU+"=======================================");
				}
				
			}
		}
		
		return paramsMap;
	}

}
